﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CSharp.Libs.Koc;
using CSharp.Libs.Koc.KernelModels;
using System.Text.RegularExpressions;
using mshtml;

namespace CSharp.Libs.WPF.UserControls
{
    /// <summary>
    /// Interaktionslogik für AutoKocBrowser.xaml
    /// </summary>
    public partial class AutoKocBrowser : UserControl
    {
        #region declarations
        private Kernel _KRNL = null;

        private AutoKocBrowserViewModel _AKBVM = null;

        private const string DisableScriptError =
            @"function noError() {
            return true;
            }
            window.onerror = noError;";
        #endregion



        #region constructor destructor
        public AutoKocBrowser()
        {
            InitializeComponent();

            _KRNL = new Kernel();

            _AKBVM = new AutoKocBrowserViewModel(_KRNL);
            DataContext = _AKBVM;

            _KRNL.AKR.ReloadServer += new KocReloader.ReloadServerEventHandler(AKR_ReloadServer);

            wbMain.Navigate("about:blank");
        }

        ~AutoKocBrowser()
        {
            _AKBVM.Dispose();
            _AKBVM = null;
        }
        #endregion



        #region event handling
        private void wbMain_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            InjectDisableScript();
        }

        void AKR_ReloadServer(object sender, ReloadServerEventArgs e)
        {
            _NavigateToUrl(String.Concat(_AKBVM.ReloadKocUrl, e.ServerId.ToString()));
        }
        #endregion



        #region private functions
        /// <summary>_NavigateToUrl</summary>
        /// <param name="Url"></param>
        /// <history>23.06.2011</history>
        private void _NavigateToUrl(
            String Url)
        {
            try
            {
                if(isValidUrl(Url))
                {
                    //_KRNL.TM.InitMonitor(wbMain.Handle);

                    Action ACT = new Action(delegate()
                    {
                        wbMain.Navigate(Url);
                    });
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, ACT);
                }
            }
            catch(Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>isValidUrl
        /// method for validating a url with regular expressions
        /// </summary>
        /// <param name="url">url we're validating</param>
        /// <returns>true if valid, otherwise false</returns>
        private Boolean isValidUrl(String url)
        {
            String pattern = @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
            Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return reg.IsMatch(url);
        }

        /// <summary>InjectDisableScript</summary>
        private void InjectDisableScript()
        {
            HTMLDocumentClass doc = wbMain.Document as HTMLDocumentClass;
            HTMLDocument doc2 = wbMain.Document as HTMLDocument;

            //Questo crea lo script per la soprressione degli errori
            IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT");
            scriptErrorSuppressed.type = "text/javascript";
            scriptErrorSuppressed.text = DisableScriptError;

            IHTMLElementCollection nodes = doc.getElementsByTagName("head");

            foreach(IHTMLElement elem in nodes)
            {
                //Appendo lo script all'head cosi è attivo
                HTMLHeadElementClass head = (HTMLHeadElementClass)elem;
                head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
            }
        }
        #endregion



        #region interface
        #region properties
        public Kernel KRNL
        {
            get
            {
                return _KRNL;
            }
        }
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
